What is alphanum-sort?
The alphanum-sort npm package is designed to provide developers with a robust solution for sorting arrays containing alphanumeric strings. Unlike the default sort in JavaScript, which can produce unexpected results with mixed content, alphanum-sort handles numbers within strings intelligently, ensuring a natural ordering. This is particularly useful for sorting lists of files, version numbers, or any other strings where numerical values are embedded within text.
What are alphanum-sort's main functionalities?
Basic alphanumeric sorting
This feature demonstrates the basic usage of alphanum-sort to sort an array of strings containing numbers in a way that 'item10' comes after 'item2', reflecting a natural ordering that humans would expect.
var alphanumSort = require('alphanum-sort');
var sortedArray = alphanumSort(['item1', 'item10', 'item2']);
console.log(sortedArray); // ['item1', 'item2', 'item10']
Case insensitive sorting
This feature shows how to perform a case-insensitive sort, treating uppercase and lowercase letters as equivalent for sorting purposes.
var alphanumSort = require('alphanum-sort');
var sortedArray = alphanumSort(['Item1', 'item10', 'Item2'], { insensitive: true });
console.log(sortedArray); // ['Item1', 'Item2', 'item10']
Sorting with custom character groupings
This feature illustrates the ability to customize sorting behavior further, such as by specifying a custom order for characters, allowing for highly tailored sorting logic.
var alphanumSort = require('alphanum-sort');
var sortedArray = alphanumSort(['item1', 'item10', 'item2'], { custom: { order: 'a' } });
console.log(sortedArray); // Custom sorting based on provided options
Other packages similar to alphanum-sort
natural-sort
Similar to alphanum-sort, natural-sort offers functionality for sorting strings containing numbers in a human-friendly way. The main difference lies in the API and additional options provided by each package for customization.
string-natural-compare
This package provides a way to compare and sort strings in a natural order, much like alphanum-sort. It focuses on performance and a minimalistic API, making it a good alternative for projects where these aspects are critical.
alphanum-sort
Alphanumeric sorting algorithm
Install
With npm do:
npm i alphanum-sort -S
Example
var sort = require('alphanum-sort');
var result = sort(['item20', 'item19', 'item1', 'item10', 'item2']);
API
alphanumSort(array, options)
options
insensitive
Type: Boolean
Default: false
Compares items case insensitively
sign
Type: Boolean
Default: false
Allows +
and -
characters before numbers
License
MIT © Bogdan Chadkin